package light.head.dao.inv;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import light.head.constant.Parm;
import light.head.enm.RESULT;
import light.head.framework.base.BaseDAO;
import light.head.framework.entity.PageBean;
import light.head.framework.utils.DateUtils;
import light.head.model.inv.InvCommodityItem;

import org.springframework.stereotype.Service;

@Service
public class InvCommodityItemDAO extends BaseDAO<InvCommodityItem, Serializable>{
	private static final String getAllByCc = "FROM InvCommodityItem ci WHERE ci.deleted = 0 AND ci.cc = ? AND ci.oc = ?";
	
	
	
	public RESULT findByMap(Integer oc, Map<String, String> map, PageBean pb){
		if (oc == null ) return null;
		StringBuffer hql = new StringBuffer("FROM InvCommodityItem ici WHERE ici.oc = ? AND ici.deleted = 0");
		List<Object> list = new ArrayList<Object>();
		
		list.add(oc);
		if (map != null) {
			String name = map.get(Parm.NAME);
			String cn = map.get(Parm.CN);
			String time1 = map.get(Parm.TIME1);
			String time2 = map.get(Parm.TIME2);
			String fast = map.get(Parm.FAST);
			if (isNotNull(name)) {
				hql.append(" AND ici.name LIKE ?");
				list.add("%" + name + "%");
			}
			if (isNotNull(cn)) {
				list.add("%" + cn + "%");
				hql.append(" AND ici.cu IN (SELECT ui.code FROM UserInfo ui WHERE ui.realName LIKE ?)");
			}
			if (isNotNull(time1)) {
				hql.append(" AND ici.ct >= ?");
				list.add(DateUtils.getDateByStr(time1, null));
			}
			if (isNotNull(time2)) {
				hql.append(" AND ici.ct <= ?");
				list.add(DateUtils.getDateByStr(time2, null));
			}if(isNotNull(fast)){
				list.add("%" + fast +"%");
				hql.append(" AND ici.fast LIKE ?");
			}
		}
		hql.append(" ORDER BY ici.code DESC");
		return findToPageBean(hql.toString(), pb, list);
	}
	
	
	public InvCommodityItem getCommodityItemByCc(Integer cc, Integer oc){
		return (InvCommodityItem)super.get(getAllByCc,cc,oc);
	}
	public RESULT update(InvCommodityItem gt) {
		if (null == gt || gt.getCode() == null) return null;
		InvCommodityItem db = this.get(gt.getCode());
		if (null == db) return RESULT.NOT_FIND;
		
		boolean ok = false;
		if ((db.getDeleted() != null) && (gt.getDeleted() != null) || (!db.getDeleted().equals(gt.getDeleted()))) {
			db.setDeleted(gt.getDeleted());
			ok = true;
		}
		if (ok)
			return super.upd(db);
		
		return RESULT.SUCCESS;
	}
	
}
